package cn.sangedon.review.data.schedule;

import cn.sangedon.review.common.constant.StatusConstant;
import cn.sangedon.review.common.domain.data.SpiderMateData;
import cn.sangedon.review.common.service.data.SpiderMateDataService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * 定时任务集中调度入口
 */
@Slf4j
@Component
public class ScheduleDispatch implements ApplicationContextAware {
    private List<IScheduleJob> scheduleJobs;

    @Autowired
    private SpiderMateDataService spiderMateDataService;

    /**
     * 定期刷新定时任务配置
     * 每天凌晨四点刷新
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void refresh() {
        if (CollectionUtils.isEmpty(scheduleJobs)) {
            log.info("无需要刷新的定时任务");
            return;
        }

        List<SpiderMateData> spiderMateDataList = spiderMateDataService.listSpider(StatusConstant.SPIDER_ON);
        log.info("开始刷新定时任务配置:jobSize:{}, {}", scheduleJobs.size(), spiderMateDataList.size());
        scheduleJobs.forEach(e -> e.runJob(spiderMateDataList));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, IScheduleJob> jobMap = applicationContext.getBeansOfType(IScheduleJob.class);
        scheduleJobs = new ArrayList<>(jobMap.values());
    }
}
